package com.laiyima.zhongjiang.linghuilv.demo.home;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.MachineAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.MachineBean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;
import com.laiyima.zhongjiang.linghuilv.demo.view.MSShadowPopupView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.SimpleCallback;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class MachineStateActivity extends SwipeBackActivity implements View.OnClickListener,ListViewPlus.ListViewPlusListener {
    private LinearLayout ms_back,no_new_machine;
    private TextView machine_find,machine_content_count;
    private ListViewPlus mListView;
    private int bCode;
    private int count, page_count, page_index;
    private MachineBean mSnListBean;
    private MachineAdapter mSnlistAdapter;
    private List<MachineBean> SnListBeanListBean = new ArrayList<>();
    private String state;
    private MSShadowPopupView popupView;

    @Override
    public void onRefresh() {
        SnListBeanListBean.clear();
        intView();
        mSnlistAdapter.notifyDataSetChanged();

        loadData(ListViewPlus.REFRESH);
        // Log.e(TAG, "onRefresh:");

    }

    @Override
    public void onLoadMore() {
        if (page_index < page_count) {
            loadData(ListViewPlus.LOAD);
        } else {
            Toast.makeText(getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
            onLoadComplete();
        }
    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {

                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:
                    onLoadComplete();
                    Toast.makeText(getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    page_index++;
                    loadMode(page_index,state);
                    Toast.makeText(getApplicationContext(), "已加载数据", Toast.LENGTH_SHORT).show();
                    break;
            }

        }



    };

    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }



    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_machine_state);
        ms_back= (LinearLayout) findViewById(R.id.ms_back);
        ms_back.setOnClickListener(this);
        machine_find= (TextView) findViewById(R.id.machine_find);
        machine_find.setOnClickListener(this);
        no_new_machine= (LinearLayout) findViewById(R.id.no_new_machine);
        mListView= (ListViewPlus) findViewById(R.id.machine_list);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);
        machine_content_count= (TextView) findViewById(R.id.machine_content_count);
        setListener();
        intView();
        setStatusBar();
    }

    private void setListener() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListViewPlus listView = (ListViewPlus) parent;
                MachineBean mTransactiondetailsBean = (MachineBean) listView.getItemAtPosition(position);
                String nid = mTransactiondetailsBean.getNid();
                String state = mTransactiondetailsBean.getState();
                Intent Taxlistintent = new Intent(MachineStateActivity.this, MachineDetActivity.class);
                Taxlistintent.putExtra("nid", nid);
                Taxlistintent.putExtra("state", state);
                startActivity(Taxlistintent);
            }
        });

    }


    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.ms_back:
                finish();
                break;
            case R.id.machine_find:
                showPartShadow(v);
                break;

        }
    }
    private void showPartShadow(final View v){
        if(popupView==null){
            popupView = (MSShadowPopupView) new XPopup.Builder(this)
                    .atView(v)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                            machine_find.setText("完成");
                        }
                        @Override
                        public void onDismiss() {
                            machine_find.setText("查询");
                            SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
                            int  t = sharedPreferences.getInt("machine_state", 0);
                            if (t==0){
                                state="";
                                findTypt("");
                            }else if(t==1){
                                state="1";
                                findTypt(state);
                            }else if(t==2){
                                state="2";
                                findTypt(state);
                            }else if (t==3){
                                state="3";
                                findTypt(state);
                            }
                            else if (t==4){
                                state="4";
                                findTypt(state);
                            }
                        }
                    })
                    .asCustom(new MSShadowPopupView(this));
        }

        popupView.show();
    }
    public void findTypt(String state){
        SnListBeanListBean.clear();
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/state");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("state", state);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    bCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObjec = new JSONObject(data);
                        count = jsonObjec.optInt("count", 0);
                        page_count = jsonObjec.optInt("page_count", 0);
                        page_index = jsonObjec.optInt("page_index", 0);
                        machine_content_count.setText(count+"");
                    }
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String sn = value.getString("sn");
                        String lId = value.getString("zId");
                        String nid = value.getString("nid");
                        String merName = value.getString("merName");
                        String state = value.getString("state");
                        String mobile = value.getString("mobile");
                        mSnListBean = new MachineBean(lId,nid,sn,merName,state,mobile);
                        SnListBeanListBean.add(mSnListBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bCode == 200) {
                    mSnlistAdapter = new MachineAdapter(getApplicationContext(), SnListBeanListBean);
                    mSnlistAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mSnlistAdapter);
                }

                if (bCode == 500) {
                    Toast.makeText(getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (SnListBeanListBean.size() == 0) {
                    no_new_machine.setVisibility(View.VISIBLE);
                } else {
                    no_new_machine.setVisibility(View.GONE);
                }
            }
        });

    }


    public void loadMode(int page_index,String state){
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/state");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("page_index", page_index);
        params.addBodyParameter("state", state);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    bCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String sn = value.getString("sn");
                        String lId = value.getString("zId");
                        String nid = value.getString("nid");
                        String merName = value.getString("merName");
                        String state = value.getString("state");
                        String mobile = value.getString("mobile");
                        mSnListBean = new MachineBean(lId,nid,sn,merName,state,mobile);
                        SnListBeanListBean.add(mSnListBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bCode == 200) {
                    mSnlistAdapter.notifyDataSetChanged();
                }

                if (bCode == 500) {
                    Toast.makeText(getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                onLoadComplete();
            }
        });



    }
public void intView(){
    SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
    String userID = sharedPreferences.getString("userID", "");
    RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/state");
    //需要带入的参数
    params.addBodyParameter("uid", userID);
     params.addBodyParameter("page_size", 10);

    // params.addBodyParameter("captcha", captcha);
    x.http().post(params, new Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String result) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                bCode = jsonObject.optInt("code", 0);
                String data = jsonObject.optString("data", null);
                JSONObject jData = new JSONObject(data);
                if (!TextUtils.isEmpty(data)) {
                    JSONObject jsonObjec = new JSONObject(data);
                    count = jsonObjec.optInt("count", 0);
                    page_count = jsonObjec.optInt("page_count", 0);
                    page_index = jsonObjec.optInt("page_index", 0);
                    machine_content_count.setText(count+"");
                }
                JSONArray list = jData.getJSONArray("list");
                for (int i = 0; i < list.length(); i++) {
                    JSONObject value = list.getJSONObject(i);
                    String sn = value.getString("sn");
                    String lId = value.getString("zId");
                    String nid = value.getString("nid");
                    String merName = value.getString("merName");
                    String state = value.getString("state");
                    String mobile = value.getString("mobile");
                    mSnListBean = new MachineBean(lId,nid,sn,merName,state,mobile);
                    SnListBeanListBean.add(mSnListBean);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (bCode == 200) {
                mSnlistAdapter = new MachineAdapter(getApplicationContext(), SnListBeanListBean);
                mSnlistAdapter.notifyDataSetChanged();
                mListView.setAdapter(mSnlistAdapter);
            }

            if (bCode == 500) {
                Toast.makeText(getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {

        }

        @Override
        public void onCancelled(CancelledException cex) {

        }

        @Override
        public void onFinished() {
            if (SnListBeanListBean.size() == 0) {
                no_new_machine.setVisibility(View.VISIBLE);
            } else {
                no_new_machine.setVisibility(View.GONE);
            }
        }
    });
}
}
